<?php

//mysql database address
define('DB_HOST','127.0.0.1');
//mysql database user
define('DB_USER','root');
//database password
define('DB_PASSWD','123456');
//database name
define('DB_NAME','order');

require_once 'mysqli.php';


$db = MySqlii::getInstance();

//$sql = "SELECT * FROM orders where expressNumber != '' AND expressTime = 0";
$sql = "SELECT * FROM orders where expressNumber != '' AND isSign = 0";
$res = $db->query($sql);

while($row = $db->fetch_array($res)) {

    echo "START ".$row['expressNumber'];

    $exp = getA($row['expressNumber']);
    
    
    if(empty($exp)) {
        echo " IS NULL \n";
        sleep(5);
        continue;
    }

    $timestr = strtotime($exp['time']);
    $time = intval(date('mdHis', $timestr));
    echo "  ". $row['expressTime']." -> ";
    echo $time."\n";

    if($row['expressTime'] != $time) {
        $sql = "update orders set expressTime = {$time} , expressLog = '{$exp['context']}' WHERE id = {$row['id']}";
        $db->query($sql);
        if(strpos($exp['context'], '签收')) {
            $isSign = 1;
            $sinSql = "UPDATE orders set isSign =1 where id = {$row['id']}";
            $db->query($sinSql);
            echo $row['expressNumber'] ." IS SIGN \n";
        }
    }
    sleep(5);

    //var_dump($time); exit;
}

function getA($expressNumber, $tot = 0) {

    //if(strlen($expressNumber) == 13) {
    //    $type = 'youzhengguonei';
    //} else {
        $type = 'zhongtong';
    //}

    //echo $type;

    $url = "http://www.kuaidi100.com/query?type=$type&postid=$expressNumber&id=1&valicode=&temp=0.9964493427759196";
    //echo $url;
    $res = file_get_contents($url);
    $result = json_decode($res, TRUE);



    return $result['data'][0];
    /*
    $data = array(
        'timestamp' => 14735869181800,
        'exname'    => 'zhongtong',
        'code'      => $expressNumber,
        'client_id' => '1F16402F-1C84-4E7C-949E-E64C622F4446',
        'uid'       => ''
    );



    $url = 'http://userappapi.kuaidi.com/Api/Courier/find';
    $ch = curl_init($url);
    curl_setopt($ch, CURLOPT_CUSTOMREQUEST, "POST");
    curl_setopt($ch, CURLOPT_POSTFIELDS,$data);
    curl_setopt($ch, CURLOPT_RETURNTRANSFER,true);


    $result = json_decode(curl_exec($ch), TRUE);


    return $result['result']['data'][0];
    */

}

/*
$sql =


$file =json_decode(file_get_contents($sql), TRUE);



var_dump($file['data'][0]['context']);
*/
